//The MIT License (MIT)
//
//Copyright (c) 2020 lihp1603
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.

package proc

import (
	"io/ioutil"
	"strconv"
	"strings"
	"time"
)

type Uptime struct {
	Total float64 `json:"total"` //seconds,Wall clock since boot
	Idle  float64 `json:"idle"`  //seconds,combined idle time of all cpus
}

func (self *Uptime) GetTotalDuration() time.Duration {
	return time.Duration(self.Total) * time.Second
}

func (self *Uptime) GetIdleDuration() time.Duration {
	return time.Duration(self.Idle) * time.Second
}

func (self *Uptime) CalculateIdlePercent(cores int16) float64 {
	// XXX
	// num2/(num1*N)     # N = SMP CPU numbers

	return self.Idle / (float64(cores) * self.Total)
}

func ReadUptime() (*Uptime, error) {
	return readUptime("/proc/uptime")
}

func readUptime(path string) (*Uptime, error) {
	b, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, err
	}
	fields := strings.Fields(string(b))
	uptime := Uptime{}
	if uptime.Total, err = strconv.ParseFloat(fields[0], 64); err != nil {
		return nil, err
	}
	if uptime.Idle, err = strconv.ParseFloat(fields[1], 64); err != nil {
		return nil, err
	}
	return &uptime, nil
}
